var jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const { JWT_SECRET } = require("../config/config.default");
const { crateUser, getUserInfo } = require("../service/user.service");
const { userRegistry } = require("../constant/err.type");
class User {
  async register(ctx, next) {
    // 1.获取数据

    let { username, password } = ctx.request.body;
    ctx.state.user = { username, password };
    // 2.操作数据库
    try {
      let res = await crateUser(username, password);
      // 3.返回结果
      ctx.body = {
        code: 0,
        msg: "成功",
        res: {
          id: res.id,
          user_name: res.username,
        },
      };
    } catch (err) {
      console.log(err);
      ctx.app.emit("error", userRegistry, ctx);
    }
  }
  async login(ctx, next) {
    const { username } = ctx.request.body;
    // 1.获取用户信息（在token的payload中），记录id,username,is_admin
    try {
      const res = await getUserInfo({ username });
      const { password, ...userMsg } = res;
      ctx.state.user = { username };
      ctx.body = {
        code: 0,
        msg: "登录成功",
        token: jwt.sign(userMsg, JWT_SECRET, { expiresIn: "20d" }),
      };
    } catch (e) {
      console.log("登录失败", e);
    }
  }
  async updatePsd(ctx, next) {
    // console.log(ctx,'ctx');
    const { username, password } = ctx.request.body;
    // console.log(username,password,'ss');
    // console.log(ctx.state.user,'user666');
    const res = await getUserInfo({ username });
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(password, salt);
    res.password = hash;
    await res.save();

    ctx.body = {
      code: 0,
      msg: "修改成功",
    };
  }
}
module.exports = new User();
